package com.baitiaojun.tenant.handler;

import cn.hutool.core.io.resource.ResourceUtil;
import com.baitiaojun.common.enums.impl.ServerExpEnums;
import com.baitiaojun.common.exception.ServerException;
import com.baitiaojun.common.utils.date.DateTimeUtils;
import com.baitiaojun.common.utils.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.Server;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.apache.ibatis.jdbc.SqlRunner;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;

@Slf4j
public class ScriptHandler {

    /**
     * 执行db脚本
     */
    public static void script(Connection connection, String tenant, String adminName, String adminPassword) throws IOException, SQLException {
        try {
            log.info("开始执行脚本初始化");
            //创建表
            ScriptRunner scriptRunner = new ScriptRunner(connection);
            scriptRunner.setErrorLogWriter(null);
            scriptRunner.setLogWriter(null);

            Reader reader = Resources.getResourceAsReader("init-sql-script/erp-crm-tenant-sample.sql");
            scriptRunner.runScript(reader);
            //添加部门
            SqlRunner sqlRunner = new SqlRunner(connection);
            String insertDept = "INSERT INTO sys_dept VALUES (100, 0, '0', '" +tenant + "', 0, '" + tenant + "', '00000000000', 'admin@admin.com', '0', '0', '" + adminName + "', '" + DateTimeUtils.getDateTime() + "', '" + adminName + "', '" + DateTimeUtils.getDateTime() + "');";
            sqlRunner.run(insertDept);
            //添加超级管理员
            String insertAdmin = "INSERT INTO sys_user (`user_id`, `dept_id`, `user_name`, `nick_name`, `user_type`, `password`, `status`, `del_flag`, `create_by`, `create_time`, `remark`) " +
                    "VALUES (1, 100, '" + adminName + "', '管理员', '00', '" + adminPassword + "', '0', '0', '" + adminName + "', '" + DateTimeUtils.getDateTime() + "', '管理员');";
            sqlRunner.run(insertAdmin);
            connection.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                connection.rollback();
            } catch (SQLException ex) {
                throw new ServerException(ServerExpEnums.EXP_DML_SCRIPT_ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServerException(ServerExpEnums.EXP_DML_SCRIPT_ERROR);
        }
    }
}
